package com.xianyun.book.gatewayimpl;

import com.alibaba.cola.exception.BizException;
import com.xianyun.book.common.util.FormatUtils;
import com.xianyun.book.convertor.UserConvertor;
import com.xianyun.book.domain.gateway.SystemUserGateway;
import com.xianyun.book.domain.user.SystemUser;
import com.xianyun.book.gatewayimpl.database.UserMapper;
import com.xianyun.book.gatewayimpl.database.dataobject.UserDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

/**
 * 用户领域层实现
 * @author ytt
 */
@Slf4j
@Component
public class SystemUserGatewayImpl implements  SystemUserGateway {

    @Resource
    private UserMapper userMapper;

    @Override
    public SystemUser loadUserByUsername(String conditionName) {
        UserDO result;
        if (FormatUtils.isNumLegal(conditionName)){
            result = userMapper.selectUserByMobile(conditionName);
        }else if (FormatUtils.isEmail(conditionName)){
            result = userMapper.selectUserByEmail(conditionName);
        } else {
            result = userMapper.selectUserByUserName(conditionName);
        }
        if (null == result){
            throw new BizException("BIZ_USER_NOT_FOUND","该用户不存在");
        }
        return UserConvertor.toDomain(result);
    }

    @Override
    public void validRegisterUniqueCondition(String conditionName, String bizCode) {

    }

    @Override
    public void registerUser(SystemUser systemUser) {
        UserDO saveData = UserConvertor.toDataObject(systemUser);
        userMapper.save(saveData);
        systemUser.setId(saveData.getId());
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void update(SystemUser systemUser) {
        UserDO data = UserConvertor.toDataObject(systemUser);
        userMapper.update(data);
    }
}
